package com.pan.note.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pan.note.dto.TimeLineNoteDto;
import com.pan.note.mapper.TimeLineNoteMapper;
import com.pan.note.service.NoteService;
import com.pan.note.util.DateToStringUtil;
import com.pan.note.vo.TimeLineNoteVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * 服务实现类
 */
@Service
public class NoteServiceImpl implements NoteService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private TimeLineNoteMapper timeLineNoteMapper;

    // 重写上传方法
    @Override
    public String upLoadNote(TimeLineNoteDto timeLineNoteDto) {
        DateToStringUtil dateToStringUtil = new DateToStringUtil();
        timeLineNoteDto.setId(0L);
        timeLineNoteDto.setCreateTime(dateToStringUtil.DateToString(new Date()));
        timeLineNoteDto.setModifyTime(dateToStringUtil.DateToString(new Date()));
        redisTemplate.opsForList().leftPush(timeLineNoteDto.getCreateTime(),timeLineNoteDto);
        int insert = timeLineNoteMapper.insert(timeLineNoteDto);
        if(insert == 1){
            return "发布成功";
        } else {
            return "发布失败";
        }
    }

    /**
     * 获取故事
     * @return 故事集
     */
    @Override
    public TimeLineNoteVo getNote(Date date) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        TimeLineNoteVo timeLineNoteVo = new TimeLineNoteVo();
        List<TimeLineNoteDto> weekNote = new ArrayList<>();
        List<String> week = new DateToStringUtil().getWeek(date);
        week.forEach(day -> {
            // 从redis中获取所有人当天的故事集
            List<TimeLineNoteDto> list = redisTemplate.opsForList().range(day, 0, -1);// 遍历list，提取相同日期的文章，转换成map集合
            weekNote.addAll(list);
        });
        timeLineNoteVo.setPages(10L);
        timeLineNoteVo.setData(weekNote);
        // 返回数据
        return timeLineNoteVo;
    }

    @Override
    public String getNoteByPage(Integer pageNum) {
        TimeLineNoteVo timeLineNoteVo = new TimeLineNoteVo();
        IPage<TimeLineNoteDto> page = new Page<>(pageNum,10);
        IPage<TimeLineNoteDto> noteDtoIPage = timeLineNoteMapper.selectPage(page,null);
        timeLineNoteVo.setData(noteDtoIPage.getRecords());
        timeLineNoteVo.setPages(noteDtoIPage.getTotal()/10+1);
        String returnJson= JSON.toJSONString(timeLineNoteVo);//关键
        return returnJson;
    }

    /**
     * 接受图片
     * @param file 要上传的图片
     * @param request 请求头
     * @param response 返回题
     * @return 标准返回接口
     */
    @Override
    public Object uploadPic(MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> map2 = new HashMap<>();
        String filename = file.getOriginalFilename(); //获取上传文件原来的名称
        String filePath = "/Users/panyi/Documents/TimeLineNoteData/";
        File temp = new File(filePath);
        if (!temp.exists()){
            temp.mkdirs();
        }
        File localFile = new File(filePath+filename);
        try {
            file.transferTo(localFile); //把上传的文件保存至本地
            System.out.println(file.getOriginalFilename()+" 上传成功");
            map.put("code", 0);//0表示成功，1失败
            map.put("msg", "上传成功");//提示消息
            map.put("data", map2);
            map2.put("src", localFile.getAbsolutePath());//图片url
            map2.put("title", filename);//图片名称，这个会显示在输入框里
        }catch (IOException e){
            e.printStackTrace();
            map.put("code", 1);//0表示成功，1失败
            map.put("msg", "失败");//提示消息
            return map;
        }
        return map;
    }
}
